<?php
namespace app\api\controller;

use think\Request;
use think\Db;

/**
 * 系统登录控制器
 * class Login
 * @package app\api\controller
 * @author 骆东 <576664583@qq.com>
 * @date 2017年8月25日15:29:14
 */
class Login{

    /**
     * 访问请求对象
     * @var Request
     */
    public $request;

    /**
     * 构造方法
     */
    public function __construct(Request $request = null){
        // 获取当前 Request 对象
        $this->request = is_null($request) ? Request::instance() : $request;
    }

    /**
     * 用户登录
     * @return string
     */
    public function index(){
        $param = $this->request->param();
        $userInfo = Db::name('AppUser')->where('phone',$param['phone'])->find();
        if($userInfo){
            if($userInfo['password'] == md5(md5($param['password']))){

                $token = md5($param['phone']+$param['password']+time());

                $info = Db::name('AppUser')->where('phone', $param['phone'])->update(['token' => $token]);

                $userInfo['token'] = $token;
                unset($userInfo['password']);

                if($info){
                    return json(
                        [
                        'code' => 200,
                        'msg'  => '登录成功',
                        'data' => $userInfo
                        ]
                    );
                }else{
                    return json(['code' => 404,'msg'  => 'token更新失败',]);
                }
                
            }else{
                return json(['code' => 404,'msg'  => '账号或密码错误',]);
            }
        }else{
            return json(['code' => 404,'msg'  => '账号或密码错误',]);
        }
    }

    /**
     * 退出登录
     */
    public function out(){
        $param = $this->request->param();
        $info = Db::name('AppUser')->where('token', $param['token'])->update(['token' => '']);
        if($info){
            return json(['code' => 200,'msg'  => '退出登录成功',]);
        }else{
            return json(['code' => 404,'msg'  => '失败',]);
        }
    }

    /**
     * 用户注册
     *
     * @return void
     */
    public function add(){
        $param = $this->request->param();
        $token = md5($param['phone']+$param['password1']+time());
        $data = [    
            'phone'    => $param['phone'],
            'password' => md5(md5($param['password1'])),
            'end_time' => date("Y-m-d H:i:s",strtotime("+1 month")),
            'token'    => $token,
        ];
        if(Db::name('AppUser')->where('phone',$data['phone'])->find()){
            return json(['code' => 404,'msg'  => '账号已存在',]);
        }
        if(Db::name('AppUser')->insert($data)){
            return json(
                [
                'code' => 200,
                'msg'  => '注册成功',
                'data' => $data
                ]
            );
        }else{
            return json(['code' => 404,'msg'  => '注册失败',]);
        }
    }

}
